package com.surveycomp.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.surverycomp.models.Challenge;
import com.surverycomp.models.Event;
import com.surveycomp.datastore.PMF;

public class WatchLinkServlet extends BaseServlet {
	private static final long serialVersionUID = 2994798736705580105L;

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Long eventId = getLong("event", request);
		if (eventId != null) {

			PersistenceManager persistenceManager = PMF.get()
					.getPersistenceManager();
			Event event = persistenceManager
					.getObjectById(Event.class, eventId);

			String secretHash = request.getParameter("h");
			if (!secretHash.equals(event.getSecretHash()))
				response.sendRedirect("/");
			else {
				DatastoreService service = DatastoreServiceFactory
						.getDatastoreService();
				Map<Key, Entity> map = service.get(event.getChallengeKeys());
				Set<Entry<Key, Entity>> entrySet = map.entrySet();

				List<Challenge> challenges = new ArrayList<Challenge>(
						entrySet.size());
				for (Entry<Key, Entity> entry : entrySet) {
					challenges.add(new Challenge(entry.getValue()));
				}
				
				HttpSession session = request.getSession(true);
				session.setAttribute("event", event);
				session.setAttribute("challenges", challenges);
				response.sendRedirect("/watchevent.jsp");
			}
		}
	}
}
